package com.cskaoyan.service;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.bean.Storage;
import com.cskaoyan.bean.StorageExample;
import com.cskaoyan.bean.vo.SystemAdminVO;
import com.cskaoyan.mapper.StorageMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author xudengfeng
 * @date 2020/12/6 18:04
 */
@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;

    //将上传的文件信息保存到数据库
    @Override
    public int savaFileInfo(Storage storage) {
        System.out.println(1);
        return storageMapper.insert(storage);
    }

    @Override
    public int uploadFile(MultipartFile file) {
        return 0;
    }

    @Override
    public SystemAdminVO queryStorageList(Integer page, Integer limit, String key, String name, String sort, String order) {
        PageHelper.startPage(page, limit);
        StorageExample storageExample = new StorageExample();
        StorageExample.Criteria criteria = storageExample.createCriteria();
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (!StringUtils.isEmpty(key)) {
            criteria.andKeyLike("%" + key + "%");
        }
        storageExample.setOrderByClause(sort + " " + order);
        List<Storage> storages = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> storagePageInfo = new PageInfo<>(storages);
        long total = storagePageInfo.getTotal();
        return SystemAdminVO.data(storages, total);
    }

    @Override
    public void updateStorage(Storage storage) {
        Date date = new Date();
        storage.setUpdateTime(date);
        storageMapper.updateByPrimaryKeySelective(storage);
    }

    @Override
    public void deleteStorage(Storage storage) {
        String url = storage.getUrl();
        String[] split = url.split("8083/");
        String key = split[1];
        String curDir = System.getProperty("user.dir");
        File file = new File(curDir + "/target/classes/static/" + key);
        file.delete();
        storageMapper.deleteByPrimaryKey(storage.getId());
    }
}
